package com.itrui.encrypted_transmission;

import com.baomidou.mybatisplus.extension.api.R;
import org.apache.tomcat.jni.FileInfo;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws Exception {
        //思路
        //在本机 的8888端口监听, 等待连接
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器端，监听" + serverSocket.getLocalPort() + "端口，等待连接");
        serverSocket.getLocalPort();
        //当没有客户端连接8888端口时，程序会 阻塞, 等待连接
        //如果有客户端连接，则会返回Socket对象，程序继续
        Socket socket = serverSocket.accept();

        receiveFile(socket, "D:\\RuiProject\\FileTest");
        serverSocket.close();

    }

    protected static void receiveFile(Socket socket, String mFilePath) throws Exception {

        File dirs = new File(mFilePath);
        if (!dirs.exists()) {
            dirs.mkdirs();
        }

        //通过socket.getInputStream() 读取客户端写入到数据通道的数据
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        DataInputStream dis = new DataInputStream(socket.getInputStream());
        String privateKeyHex = dis.readUTF();
        System.out.println("私钥是：" + privateKeyHex);

        int num = dis.readInt();
        System.out.println("文件数：" + num);

        System.out.println("正在接收第" + 1 + "个文件...");

        //获取原始加密文件
        String s = StreamUtils.streamToString(bis);
        //解密
        String decrypt = SM2Utils.decrypt(privateKeyHex, s);
        //反序列化
        MyFile myFile = JOSNUtils.deserialize(decrypt);
        //保存到文件夹中
        CodeUtils.loadFile(myFile.getFile(), "D:\\RuiProject\\Server\\" + myFile.getName());

        System.out.println("第" + 1 + "个文件接收完成！");


        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write("第" + 1 + "个文件接收完成！");
        bw.newLine();
        bw.flush();

        bis.close();
        socket.close();
    }
}
